import os
import codecs

''' 把./static/ueditor目录下的所有文件转换为UTF-8编码（会先检测） '''

def convert_to_utf8(file_path):
    # 尝试以utf-8编码读取文件
    try:
        with codecs.open(file_path, 'r', 'utf-8') as f:
            content = f.read()
        print(f"File {file_path} is already UTF-8 encoded")
        return
    except UnicodeDecodeError:
        pass
    
    # 以系统默认编码读取文件
    try:
        with open(file_path, 'r', encoding='gbk') as f:
            content = f.read()
    except UnicodeDecodeError:
        try:
            with open(file_path, 'r', encoding='latin1') as f:
                content = f.read()
        except UnicodeDecodeError:
            print(f"Could not read file {file_path}")
            return
    
    # 以UTF-8编码写入文件
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    print(f"Converted {file_path} to UTF-8")

def convert_directory(directory):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(('.js', '.css', '.html', '.json', '.txt', '.md')):
                file_path = os.path.join(root, file)
                convert_to_utf8(file_path)

if __name__ == "__main__":
    convert_directory('./static/ueditor')
    print("Encoding conversion completed!")
    